package com.ymk.cmd;


import com.ymk.base.cmd.ACmd;
import com.ymk.base.cmd.CmdSign;
import com.ymk.base.exception.MallException;
import com.ymk.base.mybatis.Pagination;
import com.ymk.base.utlis.ParamsBuilder;
import com.ymk.core.code.cmd.RbacCmdCode;
import com.ymk.bo.rbac.RbacRoleBO;
import com.ymk.bo.rbac.RbacRolePermBO;
import com.ymk.service.IRbacRolePermService;
import com.ymk.service.IRbacRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Service
public class RbacRolePostCmd extends ACmd {

    @Override
    public CmdSign executeSop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        RbacRoleBO rbacRoleBO = super.getData(sign, RbacRoleBO.class);
        super.setCreatedData(sign,rbacRoleBO);
        this.rbacRoleService.post(rbacRoleBO);
        rbacRoleBO.getPermIdList().forEach(res -> {
            RbacRolePermBO rbacRolePermBO = new RbacRolePermBO();
            rbacRolePermBO.setRoleId(rbacRoleBO.getId());
            rbacRolePermBO.setPermId(res);
            this.rbacRolePermService.post(rbacRolePermBO);
        });
        return respSign;
    }

    @Override
    public CmdSign executeMop(HttpServletRequest request, CmdSign sign) throws Exception {
        CmdSign respSign = new CmdSign(sign);
        RbacRoleBO rbacRoleBO = super.getData(sign, RbacRoleBO.class);

        // 获取本次新增角色的数据
        ParamsBuilder paramsBuilder = ParamsBuilder.newBuild()
                .addParam("name", rbacRoleBO.getName())
                .addParam("mchId",rbacRoleBO.getMchId());

        Pagination pagination = sign.buildPage();
        pagination.setParams(paramsBuilder.build());
        List<RbacRoleBO> rbacRoleBOS = this.rbacRoleService.listForPage(pagination);

        if (!rbacRoleBOS.isEmpty()){
           throw new MallException("该角色已存在");
        }

        super.setCreatedData(sign,rbacRoleBO);
        this.rbacRoleService.post(rbacRoleBO);
        respSign.setSource(super.getSource(rbacRoleBO));


//        rbacRoleBO.getPermIdList().forEach(res -> {
//            RbacRolePermBO rbacRolePermBO = new RbacRolePermBO();
//            rbacRolePermBO.setRoleId(rbacRoleBO.getId());
//            rbacRolePermBO.setPermId(res);
//            this.rbacRolePermService.post(rbacRolePermBO);
//        });
        return respSign;
    }


    @Override
    public String getCmdCode() {
        return RbacCmdCode.RBAC_ROLE_POST;
    }

    @Autowired
    private IRbacRoleService rbacRoleService;
    @Autowired
    private IRbacRolePermService rbacRolePermService;
}
